package com.xc.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // 创建默认Redis模板
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // Redis的String序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // 设置redis的key的序列化为String
        template.setKeySerializer(stringRedisSerializer);
        // 设置redis的hash结构的hashKey的序列化为String
        template.setHashKeySerializer(stringRedisSerializer);

        // JSON序列化
        Jackson2JsonRedisSerializer<Object> redisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        // 虽然方法被删除，但是不写localDateTime序列化都直接失败
        redisSerializer.setObjectMapper(objectMapper());

        // value是Object，有可能是entity，用JSON序列化
        template.setValueSerializer(redisSerializer);
        // Hash的value也用JSON序列化
        template.setHashValueSerializer(redisSerializer);
        // 初始化设置的配置
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public ObjectMapper objectMapper(){
        // 序列化与反序列化都是通过该对象调用
        ObjectMapper objectMapper = new ObjectMapper();
        // PropertyAccessor.ALL 表示所有修饰符修饰的属性，而 JsonAutoDetect.Visibility.ANY 则表示这些属性的可见性设置为“任何可见”
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        SimpleModule myModule = new SimpleModule();
        // 添加序列化器/反序列化器
        myModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        myModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        objectMapper.registerModule(myModule);
        return objectMapper;
    }
}
